package com.weishuang.monitor.employee.jobhandler.impl;

import cn.hutool.json.JSONUtil;
import com.weishuang.monitor.employee.commons.LocalDateTimeUtils;
import com.weishuang.monitor.employee.commons.SendUtils;
import com.weishuang.monitor.employee.entity.ServerDiskInfo;
import com.weishuang.monitor.employee.entity.ServerDiskInfoRequest;
import com.weishuang.monitor.employee.jobhandler.ServerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import oshi.SystemInfo;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

public class ServerDiskInfoHandler implements ServerHandler {

    public final static Logger logger = LoggerFactory.getLogger(ServerDiskInfoHandler.class);

    private static final String upServerDiskInfoUrl = "/api/serversBaseInfo/upServerDiskInfo";

    private static String notAddDiskType = "rootfs";

    @Override
    public void run() {
        logger.debug("开始执行磁盘进行更新");
        SystemInfo si = new SystemInfo();
        OperatingSystem operatingSystem = si.getOperatingSystem();
        FileSystem fileSystem = operatingSystem.getFileSystem();
        List<OSFileStore> osFileStores = fileSystem.getFileStores();
        List<ServerDiskInfo> serverDiskInfos = new ArrayList<>();
        osFileStores.forEach(osFileStore -> {
            if (!notAddDiskType.equals(osFileStore.getType())) {
                ServerDiskInfo serverDiskInfo = new ServerDiskInfo();
                serverDiskInfo.setDiskUuid(osFileStore.getUUID());
                serverDiskInfo.setDiskName(osFileStore.getName());
                serverDiskInfo.setDiskLabel(osFileStore.getLabel());
                serverDiskInfo.setDiskType(osFileStore.getType());
                serverDiskInfo.setDiskMount(osFileStore.getMount());
                serverDiskInfo.setDiskDescription(osFileStore.getDescription());
                serverDiskInfo.setDiskSpace(osFileStore.getTotalSpace());
                serverDiskInfo.setDiskSpaceFree(osFileStore.getUsableSpace());
                serverDiskInfo.setUpdatedTime(LocalDateTimeUtils.getUtcToShanghaiDate(LocalDateTime.now(ZoneOffset.UTC)));
                serverDiskInfos.add(serverDiskInfo);
            }
        });
        try {
            String disksJson = JSONUtil.toJsonStr(serverDiskInfos);
            ServerDiskInfoRequest diskInfoRequest = new ServerDiskInfoRequest();
            diskInfoRequest.setDiskInfos(disksJson);
            String s = SendUtils.sendRequest(upServerDiskInfoUrl, diskInfoRequest);
            logger.debug(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
